package com.ux.iot.jetlinks.service.websocket.handler;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ux.iot.core.bo.AmqpData;
import com.ux.iot.core.service.MessageHandlerManager;
import com.ux.iot.jetlinks.contant.JetlinkTopicContants;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@AllArgsConstructor
public class JetlinksSampleMessageListener implements JetlinksMessageListener {
    MessageHandlerManager messageHandlerManager;
    @Override
    public void onMessage(String  message) {
        processMessage(message);

    }
    /**
     * {"payload":{"code":"REQUEST_HANDLING","deviceId":"pr-3008-ws-n01-test-circular","functionId":"sendCommRTU","message":"error.code.request_handling","messageId":"1451025447825575936","messageType":"INVOKE_FUNCTION_REPLY","success":true,"timestamp":1634786400168},"requestId":"4f0ba2f6-a8b4-4050-b41b-da93238cb7c8","topic":"/device-message-sender/pr-3008-ws-n01-test-circular/*","type":"result"}
     * 在这里处理您收到消息后的具体业务逻辑。
     */
    private  void processMessage(String message) {
        log.info("消息具体处理类{}",message);

        JSONObject ob= JSON.parseObject(message);
        JSONObject payload=ob.getJSONObject("payload");
        if(payload==null){
            messageHandlerManager.handler(AmqpData.builder().topic("void").build());
        }else{
            String type=payload.getString("messageType");
            if(StrUtil.isEmpty(type)){
                String topic=ob.getString("topic");
                if(topic.contains("/rule-engine/device/alarm/")){
                    type= JetlinkTopicContants.ALARM;
                }
            }
            AmqpData data=AmqpData.builder()
                    .messageId(ob.getString("requestId"))
                    .topic(type)
                    .msg(JSON.toJSONString(payload,SerializerFeature.DisableCircularReferenceDetect))
                    .build();
            messageHandlerManager.handler(data);
        }


    }
}
